/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package fsd.semana3.aula.echoeventlinhas;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;

/**
 *
 * @author nfsa
 */
public class EchoServerMain {

    public static void main() throws Exception
    {
        ServerSocketChannel ssocket = SelectorProvider.provider().openServerSocketChannel();
        ssocket.configureBlocking(false);
        ssocket.socket().bind(new InetSocketAddress(12345));

        Selector selector = Selector.open();
        ssocket.register(selector, SelectionKey.OP_ACCEPT);

        LineListener listener = new LineListener() {

            public void onReadLine(String line) {
                System.out.println("Recebida linha : "+line);
            }
        };

        while (selector.isOpen())
        {
            selector.select();
            for (SelectionKey key : selector.selectedKeys())
            {
                if (key.isAcceptable())
                {
                    SocketChannel socket = ssocket.accept();
                    socket.configureBlocking(false);
                    SelectionKey key2 = socket.register(selector, SelectionKey.OP_READ);
                    Echo echo = new Echo(key2);
                    echo.setListener(listener);
                    key2.attach(echo);
                }
                if (key.isReadable())
                {
                    Echo att = (Echo) key.attachment();
                    att.handleRead();
                }
                if (key.isValid() && key.isWritable())
                {
                    Echo att = (Echo) key.attachment();
                    att.handleWrite();
                }
            }
            selector.selectedKeys().clear();
        }
    }
}
